
<template>
    <rx-dialog @handOk="handleSubmit" @cancel="cancel">
        <rx-layout>
            <div slot="center">
                <a-form-model ref="form"  :model="mdl" :rules="rules" :layout="'vertical'">
                    <a-form-model-item  :label="i18n('form.selForm','选择表单')" prop = "formName">
                        <rx-input-button    @click="selectForm" v-model="mdl.form"></rx-input-button>
                    </a-form-model-item>
                    <a-form-model-item  :label="i18n('form.selRole','角色')"   prop = "roles">
                        <rx-input-button    @click="selectRoles" v-model="mdl.role"></rx-input-button>
                    </a-form-model-item>
                    <a-form-model-item  :label="i18n('form.mapSetting','映射配置')"  prop = "config">
                        <div  style="text-align: right;margin-bottom: 10px;">
                            <a-button-group class="addbutton" style="text-align: right;">
                                <button @click="add()"><i class="iconfont iconadd"></i></button>
                                <button @click="remove()"><i class="iconfont icontrash"></i></button>
                                <button @click="moveUp()"><i class="iconfont iconshang"></i></button>
                                <button @click="moveDown()"><i class="iconfont iconxia"></i></button>
                                <button @click="moveTopUp()"><i class="iconfont iconzhiding"></i></button>
                                <button @click="moveBottom()"><i class="iconfont iconzhidi"></i></button>
                            </a-button-group>
                        </div>

                        <rx-grid
                            ref="table"
                            :bordered="true"
                            :showColumnsMenu="true"
                            :dataSource="mappings"
                            :columns="columns"
                            :allowRowSelect="true"
                            :heightAuto="true"
                            :multiSelect="true"
                            :showPage="false"
                            idField="index_"

                        >
                            <template slot="field" slot-scope="{text, record, index}">
                                <a-select v-model="record.field" :options="getFields(record)" allowClear ></a-select>
                            </template>
                            <template slot="userField" slot-scope="{text, record, index}">
                                <a-select v-model="record.userField" :options="getUserFields(record)" v-if="showUserField(record)"></a-select>
                            </template>
                            <template slot="mapType" slot-scope="{text, record, index}">
                                <a-select :options="getMapTypes(record)"  v-model="record.mapType" ></a-select>
                            </template>
                        </rx-grid>
                    </a-form-model-item>
                    <a-form-model-item  :label="i18n('list.status','状态')" prop = "status">
                        <a-radio-group v-model="mdl.status" :options="statusOptions" ></a-radio-group>
                    </a-form-model-item>
                </a-form-model>


            </div>
        </rx-layout>
    </rx-dialog>
</template>
<script>
    import FormUserMappingApi from '@/api/form/core/formUserMapping';
    import Vue from "vue";
    import {RxDialog, BaseFormModel, Util,Dialog} from '@lowcode/jpaas-common-lib';
    import DialogBox from "@/assets/js/DialogBox";
    import FormBoDefApi from "@/api/form/bo/formBoDef.js";

    export default {
        name: 'FormUserMappingEdit',
        mixins:[BaseFormModel],
        components: {
            RxDialog,
        },
        data(){
            return {
                selectedRowKeys:[],
                selectedRows:[],
                rules: {
                },
                complexJson:{
                    main: {
                        form: {text: "formName", value: "formId"},
                        role: {text: "roleName", value: "roleId"}
                    }
                },
                columns:[
                    {title: this.i18n('form.field',"表单字段") , dataIndex: 'field', scopedSlots: {customRender: 'field'},},
                    {title: this.i18n('form.mapType',"映射类型"), dataIndex: 'mapType', scopedSlots: {customRender: 'mapType'}},
                    {title: this.i18n('form.userField',"用户表字段"), dataIndex: 'userField',scopedSlots: {customRender: 'userField'}},
                ],
                //映射配置
                mappings:[],
                //映射类型
                mapTypes:[
                    {value:"name",label:this.i18n('form.name',"姓名") ,unique:true,msg:this.i18n('form.nameRequire',"姓名必填"),require:true},
                    {value:"account",label:this.i18n('form.account',"账号") ,unique:true,msg:this.i18n('form.accountRequire',"账号必须配置"),require:true},
                    {value:"loginField",label:this.i18n('form.loginField',"登录字段"),unique:false,require:false},
                    {value:"loginMapField",label:this.i18n('form.loginMapField',"登录映射字段"),unique:false,require:false},
                    {value:"password",label:this.i18n('form.password',"密码"),unique:true,msg:this.i18n('form.pwdRequire',"密码必填"),require:true},
                    {value:"mapField",label:this.i18n('form.mapField',"映射字段"),unique:false,require:false}],
                //OS_USER字段
                osUserFields:[
                    {value:"FULLNAME_",label:this.i18n('form.FULLNAME_',"姓名")},
                    {value:"ENTRY_TIME_",label:this.i18n('form.ENTRY_TIME_',"入职时间")},
                    {value:"MOBILE_",label:this.i18n('form.MOBILE_',"手机")},
                    {value:"EMAIL_",label:this.i18n('form.EMAIL_',"邮件")},
                    {value:"BIRTHDAY_",label:this.i18n('form.BIRTHDAY_',"生日")},
                    {value:"SEX_",label:this.i18n('form.SEX_',"性别")},
                    {value:"ADDRESS_",label:this.i18n('form.ADDRESS_',"地址")},
                    {value:"URGENT_",label:this.i18n('form.URGENT_',"紧急联系人")},
                    {value:"URGENT_MOBILE_",label:this.i18n('form.URGENT_MOBILE_',"紧急联系人手机")},
                    {value:"QQ_",label:this.i18n('form.QQ_',"QQ号")}
                ],
                /**
                 * os_user 可登录字段.
                 */
                osUserLoginFields:[
                    {value:"MOBILE_",label:this.i18n('form.MOBILE_',"手机")},
                    {value:"EMAIL_",label:this.i18n('form.EMAIL_',"邮件")}
                ],
                statusOptions:[
                    {value:1,label:this.i18n('list.enable',"启用")},
                    {value:0,label:this.i18n('list.disable',"禁用")}
                ],
                formFields:[]
            }

        },
        methods: {
            i18n(name,text,key){
                return this.$ti18(name,text,"formUserMapping",key);
            },
            onload_(data){
                if(!data){
                    //新增时可用.
                    Vue.set(this.mdl,"status",1);
                    this.loadDefault();
                    return;
                }
                let boDefId = data.boDefId;
                this.loadFormFields(boDefId);
                this.initMapping(data);
            },
            /**
             * 初始化配置.
             * @param data
             */
            initMapping(data){
                let fields=JSON.parse( data.config);
                for(let field of fields){
                    field.index_=Util.randomId();
                }
                this.mappings=fields;
            },
            get(id){
                return FormUserMappingApi.get(id);
            },
            save(){
                this.mdl.config=JSON.stringify(this.mappings);
                return FormUserMappingApi.save(this.mdl);
            },
            /**
             * 选择表单,并记载数据.
             * @param vm
             */
            selectForm(vm){
                let self_ = this;
                let config = {curVm: this, widthHeight: ['1100px', '650px'],data:{multiSelect:false}};
                DialogBox.openForm(config, function (data) {
                       vm.setVal(data.id,data.name);
                       self_.loadFormFields(data.bodefId);
                    }
                );
            },
            /**
             * 根据业务模型ID加载表单字段数据.
             * @param boDefId 业务模型ID
             */
            loadFormFields(boDefId){
                FormBoDefApi.getBoIdFields(boDefId).then(res=>{
                    let boAttrs= res.boAttrs;
                    this.formFields=boAttrs.map(item=>{
                        return {value:item.name,label:item.comment}
                    })
                })
            },
            onSelectChange(selectedRowKeys, selectedRows){
                this.selectedRowKeys = selectedRowKeys;
                this.selectedRows = selectedRows
            },
            moveUp() {
                this.$refs.table.moveUp();
            },
            moveDown() {
                this.$refs.table.moveDown();
            },
            moveTopUp(){
                this.$refs.table.moveTopUp();
            },
            moveBottom(){
                this.$refs.table.moveBottomUp();
            },
            add(){
                this.mappings.push({
                    index_: Util.randomId(),
                    field:"",
                    mapType:"",
                    userField:"",
                });
            },
            remove(){
                this.$refs.table.removeRows();
            },
            loadDefault(){
                let defaultAry=[
                    {
                        index_: Util.randomId(),
                        field:"",
                        mapType:"name",
                        userField:"",
                    },{
                        index_: Util.randomId(),
                        field:"",
                        mapType:"account",
                        userField:"",
                    },{
                        index_: Util.randomId(),
                        field:"",
                        mapType:"password",
                        userField:"",
                    }];
                this.mappings.push(...defaultAry);
            },
            /**
             * 是否显示用户字段.
             * @param record
             * @returns {boolean}
             */
            showUserField(record){
                let aryType=["name","account","loginField","password"];
                return !aryType.includes(record.mapType);
            },
            /**
             * 获取用户字段.
             * @param reord
             * @returns
             */
            getUserFields(reord){
                if(reord.mapType=="loginMapField"){
                    return this.osUserLoginFields;
                }else{
                    return this.osUserFields;
                }
                return [];
            },
            /**
             * 获取表单字段.
             * @param record
             * @returns {*[]}
             */
            getFields(record){
                //选中的记录
                let mapFields=[];
                for(let item of this.mappings){
                    if(item.field==record.field){
                        continue;
                    }
                    mapFields.push(item.field);
                }
                let rtnFields=[];
                for(let field of this.formFields){
                    if(!mapFields.includes(field.value) ){
                        rtnFields.push(field);
                    }
                }
                return rtnFields;
            },
            /**
             * 获取映射类型.
             * @param record
             * @returns {*[]}
             */
            getMapTypes(record){
                //选中的类型
                let types=[];
                for(let item of this.mappings){
                    types.push(item.mapType);
                }
                let rtnTypes=[];
                for(let type of this.mapTypes){
                    if(type.value==record.mapType){
                        rtnTypes.push(type);
                    }
                    else{
                        if(type.unique && types.includes(type.value)){
                            continue;
                        }
                        rtnTypes.push(type);
                    }
                }
                return rtnTypes;
            },
            /**
             * 选择角色.
             * @param vm
             */
            selectRoles(vm){
                let config = {
                   curVm: this,
                   data: {
                       single:false,
                       dimId:'2',
                       showDimId:false
                   },
                   widthHeight: ['800px','600px']
                };
                Dialog.openGroupDialog(config,(vueVm,data)=>{
                    let groupIds=[];
                    let groupNames=[];
                    if(!data || data.length==0){
                        vm.setVal("","");
                        return ;
                    }
                    for(let group of data){
                        groupIds.push(group.groupId);
                        groupNames.push(group.name);
                    }
                    vm.setVal(groupIds.join(","),groupNames.join(","))
                })
            },
            /**
             * 提交时验证表单.
             * @param data
             * @returns {boolean}
             */
            validForm(data){
                if(!data.form){
                    this.$message.warn(this.i18n('form.setForm',"请配置表单!"));
                    return false;
                }
                if(!data.role){
                    this.$message.warn(this.i18n('form.setRole',"请选择角色!"));
                    return false;
                }
                let requireMapTypes=this.mapTypes.filter(item=>item.require==true);
                for(let mapType of requireMapTypes){
                    let result= this.mappings.filter(item=> item.mapType == mapType.value);
                    if(result.length==0){
                        this.$message.warn(mapType.msg);
                        return false;
                    }
                }
                return true;
            }
        }

    }
</script>
<style>
    .relick a{
        margin-right: 10px;
    }

</style>
